package com.ruoyi.ysVideo.controller;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.Threads;
import com.ruoyi.ysVideo.domain.MyGetVideoAutoTask;
import com.ruoyi.ysVideo.domain.MyVideoAutoTask;
import com.ruoyi.ysVideo.domain.AppInfo;
import com.ruoyi.ysVideo.domain.MyPresetInfo;
import com.ruoyi.ysVideo.domain.MyToken;
import com.ruoyi.ysVideo.service.EzvizService;
import com.ruoyi.ysVideo.service.EzvizVideoAutoTaskService;
import com.ruoyi.ysVideo.utls.MyTools;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @program: my-ruoyi-master_202130504106_李航
 * @description:
 * @author: LiHang
 * @create: 2022-01-10 16:10
 **/
@Api("视频定时任务处理类")
@Slf4j
@RestController
@RequestMapping("/EzvizVideoAutoTask")
public class EzivzVideoAutoTaskController {



    /**
     * 萤石云 Token Url
     */
    @Value("${ys7.ys7tokenUrl}")
    private String ys7tokenUrl;

    /**
     * 萤石云 获取-播放地址 Url
     */
    @Value("${ys7.ys7LiveAddress}")
    private String ys7LiveAddress;

    /**
     * 萤石云 抓拍图片地址
     */
    @Value("${ys7.ys7CaptureUrl}")
    private String ys7CaptureUrl;

    /**
     * 萤石云 添加预置位
     */
    @Value("${ysOperation.ys7PresetAdd}")
    private String ys7PresetAdd;

    /**
     * 萤石云 调用预置位
     */
    @Value("${ysOperation.ys7PresetMove}")
    private String ys7PresetMove;


    /**
     * 萤石云 清除预置位
     */
    @Value("${ysOperation.ys7PresetClear}")
    private String ys7PresetClear;

    /**
     * 存储文件的路径
     */
    @Value("${ruoyi.profile}")
    private String profile;

    @Autowired
    private EzvizService ezvizService;



    /**
     * service
     */
    @Autowired
    private EzvizVideoAutoTaskService videoAutoTaskService;

    @ApiOperation("查看所有定时任务")
    @GetMapping("/selectAllTask")
    public AjaxResult selectAllTask(){
        return AjaxResult.success(videoAutoTaskService.selectAllTask());
    }

    @ApiOperation("根据设备序列号查看所有定时任务")
    @GetMapping("/selectAllTaskBydeviceSerial")
    public AjaxResult selectAllTaskBydeviceSerial(MyVideoAutoTask myVideoAutoTask){
        return AjaxResult.success(videoAutoTaskService.selectAllTaskBydeviceSerial(myVideoAutoTask));
    }

    @ApiOperation("开始自动任务")
    @PostMapping("/startTask")
    public AjaxResult startTask(MyGetVideoAutoTask myGetVideoAutoTask) {
        String cron="";
        MyVideoAutoTask myVideoAutoTask = new MyVideoAutoTask();
        if(myGetVideoAutoTask.getIsEachHour()==1){
            cron= myGetVideoAutoTask.getSecond().toString()+" "+ myGetVideoAutoTask.getMinute().toString()+"  * * * ?";
        }else {
            cron= myGetVideoAutoTask.getSecond().toString()+" "+ myGetVideoAutoTask.getMinute().toString()+" "+ myGetVideoAutoTask.getHour().toString()+ " * * ?";
        }
        if(myGetVideoAutoTask.getIsNowPreset()==1){
            MyPresetInfo presetInfo = new MyPresetInfo();
            presetInfo.setDeviceSerial(myGetVideoAutoTask.getDeviceSerial());
            presetInfo.setRemark(myGetVideoAutoTask.getRemark());
            //先通过app_key和app_secret获取token
            AppInfo info = ezvizService.selectMyAppInfo(myGetVideoAutoTask.getDeviceSerial());
            MyToken myToken = MyTools.get_access_token(info.getAppKey(),info.getAppSecret());


//        String getLiveAddressUrl = ys7LiveAddress + "?accessToken=" + videoDao.getAccessToken() + "&deviceSerial=" + videoDao.getDeviceSerial();
            String getLiveAddressUrl = ys7PresetAdd + "?accessToken=" + myToken.getAccess_token() + "&deviceSerial=" + presetInfo.getDeviceSerial()+"&channelNo=1";
            log.info(getLiveAddressUrl);
            try {
                ResponseEntity<String> responseEntity = Threads.postRequest(getLiveAddressUrl);
                /* 拿到data数据 */
                JSONObject jsonObject = JSONObject.parseObject(responseEntity.getBody());
                String code=jsonObject.get("code").toString();
                if(code.equals("60008")){
                    return AjaxResult.error("添加的预置点个数达到上限（12个），请清除不需要的预置点后在进行添加操作");
                }else if(code.equals("200")) {
                    Integer nowIndex = Integer.valueOf(jsonObject.getJSONObject("data").get("index").toString());
                    log.info(String.valueOf(nowIndex));
                    presetInfo.setIndexId(nowIndex);
                    ezvizService.insertMyPreset(presetInfo);

                    myVideoAutoTask.setPresetIndexId(nowIndex);
                    myVideoAutoTask.setDeviceSerial(myGetVideoAutoTask.getDeviceSerial());
                    myVideoAutoTask.setCron(cron);
                    int id = videoAutoTaskService.insertAutoTask(myVideoAutoTask);
                    return AjaxResult.success(id);
                }else {
                    return AjaxResult.error("未知错误，请联系管理员，错误码："+code);
                }
            } catch (Exception e) {
                System.out.println(e);
                return AjaxResult.error("添加预置位出错！请重试!");
            }
        }else {
            // 先判断该预制点是否已经有定时任务，有则删除原来的相同序列号与预制点的定时任务，然后进行insert（新需求：如果一个预制点已经存在定时任务，再新增定时任务就覆盖原来的定时任务）
            List<Integer> res_id = videoAutoTaskService.existAutoTask(myGetVideoAutoTask);
            if(res_id.size()!=0){
                res_id.forEach(el->videoAutoTaskService.deleteAutoTask(el));
            }
            myVideoAutoTask.setPresetIndexId(myGetVideoAutoTask.getIndexId());
            myVideoAutoTask.setDeviceSerial(myGetVideoAutoTask.getDeviceSerial());
            myVideoAutoTask.setCron(cron);
            int id = videoAutoTaskService.insertAutoTask(myVideoAutoTask);
            return AjaxResult.success(id);
        }
    }

    /**
     * 根据id关闭任务
     **/
    @GetMapping("/stopTask")
    public AjaxResult stopCron(Integer id) {

        videoAutoTaskService.deleteAutoTask(id);
        return AjaxResult.success(id);
    }

    /**
     * 修改自动任务
     **/
    @PostMapping("/changeTask")
    public AjaxResult changeTask(MyGetVideoAutoTask myGetVideoAutoTask) {
        videoAutoTaskService.deleteAutoTask(myGetVideoAutoTask.getId());
        String cron="";
        MyVideoAutoTask myVideoAutoTask = new MyVideoAutoTask();
        if(myGetVideoAutoTask.getIsEachHour()==1){
            cron= myGetVideoAutoTask.getSecond().toString()+" "+ myGetVideoAutoTask.getMinute().toString()+"  * * * ?";
        }else {
            cron= myGetVideoAutoTask.getSecond().toString()+" "+ myGetVideoAutoTask.getMinute().toString()+" "+ myGetVideoAutoTask.getHour().toString()+ " * * ?";
        }
        myVideoAutoTask.setPresetIndexId(myGetVideoAutoTask.getIndexId());
        myVideoAutoTask.setDeviceSerial(myGetVideoAutoTask.getDeviceSerial());
        myVideoAutoTask.setCron(cron);
        int id = videoAutoTaskService.insertAutoTask(myVideoAutoTask);
        return AjaxResult.success(id);
    }
}
